package com.app.manage.moudles.push.service.impl;

import cn.hutool.core.io.FileUtil;
import com.app.manage.components.CommonComponent;
import com.app.manage.moudles.app.dao.TAppDao;
import com.app.manage.moudles.app.dao.TAppServerDao;
import com.app.manage.moudles.app.entity.TApp;
import com.app.manage.moudles.app.po.AppServerPo;
import com.app.manage.moudles.push.constants.FileStatusEnums;
import com.app.manage.moudles.push.dao.TPushTaskDao;
import com.app.manage.moudles.push.dao.TPushUploadDao;
import com.app.manage.moudles.push.entity.TPushUpload;
import com.app.manage.moudles.server.dao.TServerDao;
import com.app.manage.moudles.system.dao.TLogDao;
import com.app.manage.utils.FileSizeTranUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.app.manage.moudles.push.dao.TPushTaskAppDao;
import com.app.manage.moudles.push.entity.TPushTaskApp;
import com.app.manage.moudles.push.service.TPushTaskAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (TPushTaskApp)表服务实现类
 *
 * @author makejava
 * @since 2025-06-04 10:51:55
 */
@Service("tPushTaskAppService")
@Slf4j
public class TPushTaskAppServiceImpl extends ServiceImpl<TPushTaskAppDao, TPushTaskApp> implements TPushTaskAppService {



    @Resource
    private TPushUploadDao pushUploadDao;

    @Resource
    private TAppDao appDao;

    @Resource
    private TAppServerDao appServerDao;

    @Resource
    private CommonComponent commonComponent;



    @Override
    public Map<String, Object> listAppByTask(Integer taskId, List<Integer> appIdList) {
        List<String>  hasList = new ArrayList<>();
        List<String>  allList = new ArrayList<>();

        //查询应用列表-所有的jar
        List<TApp> appList = appDao.selectList(new LambdaQueryWrapper<TApp>().in(TApp::getId,appIdList));
        for(TApp t : appList){
            allList.add(t.getJarName());
        }

        //查询上传的
        List<TPushTaskApp>  pushTaskAppList = list(new LambdaQueryWrapper<TPushTaskApp>().eq(TPushTaskApp::getTaskId,taskId));
        for(TPushTaskApp t  : pushTaskAppList){
            hasList.add(t.getAppJarName());
        }
        List<String>  noList = new ArrayList<>(allList);
        noList.removeAll(hasList);

        return new HashMap<String, Object>(){{
            put("all",String.join(",",allList));
            put("noUpload",String.join(",",noList));
            put("hasUpload",String.join(",",hasList));

        }};
    }

    @Override
    public List<String> uploadJarsAndGenTaskApps(String path , MultipartFile[] files, Integer taskId, List<Integer> appIdList) throws Exception {
        List<String>  uploadFileNameList = new ArrayList<>();

        if(CollectionUtils.isEmpty(appIdList)){
            return new ArrayList<>();
        }
        //新建文件夹
        path = path.endsWith(File.separator)?path:path+File.separator;
        if(!FileUtil.exist(path)){
            FileUtil.mkdir(path);
        }

        //根据应用查询应用服务器
        Map<String,List<AppServerPo>> jarNameAppServerMap = findJarNamePo(appIdList);

        //生成实力
        for(MultipartFile f : files){
            List<AppServerPo> poList = jarNameAppServerMap.get(f.getOriginalFilename());
            if(CollectionUtils.isEmpty(poList)){
                continue;
            }
            uploadFileNameList.add(f.getOriginalFilename());

            //生成本地上传文件路径
            String localFilePath = path +f.getOriginalFilename();
            //1.生成上传文件
            TPushUpload u = new TPushUpload();
            u.setTaskId(taskId);
            u.setFileName(f.getOriginalFilename());
            u.setFileLength(FileSizeTranUtils.kbTo(f.getSize()));
            u.setLastDate(new Date());
            u.setFilePath(path +f.getOriginalFilename());
            u.setUpdateTime(new Date());
            u.setCreateTime(new Date());
            u.setFileStatus(FileStatusEnums.ADD.getStatus());
            pushUploadDao.insert(u);


            //删除历史的实例
            remove(new LambdaQueryWrapper<TPushTaskApp>().eq(TPushTaskApp::getTaskId,taskId).eq(TPushTaskApp::getAppId,poList.get(0).getAppId()));

            //生成上传实例
            for(AppServerPo po : poList){
                TPushTaskApp p = new TPushTaskApp();
                p.setTaskId(taskId);
                p.setAppId(po.getAppId());
                p.setServerId(po.getServerId());
                p.setServerIp(po.getServerIp());
                p.setAppName(po.getAppName());
                p.setAppCode(po.getAppCode());
                p.setAppJarName(po.getJarName());
                p.setLocalPath(localFilePath);
                p.setUploadPath(po.getAppPath());
                p.setPushActive(1);
                save(p);
            }

            //上传文件
            FileUtil.writeBytes(f.getBytes(),localFilePath);
        }
        //删除不需要的
        List<TPushTaskApp>  noExistList = list(new LambdaQueryWrapper<TPushTaskApp>().eq(TPushTaskApp::getTaskId,taskId).notIn(TPushTaskApp::getAppId,appIdList));
        for(TPushTaskApp a : noExistList){
            removeById(a.getId());
            FileUtil.del(a.getLocalPath());
        }

        //添加日志
        commonComponent.addTaskLog("上传了应用包",String.join(",",uploadFileNameList),taskId);

        return uploadFileNameList;
    }


    /**
     * 获取
     * @param appIdList
     * @return
     */
    private Map<String, List<AppServerPo>> findJarNamePo(List<Integer> appIdList){
        List<AppServerPo> appServerPoList = appServerDao.listAppPo(appIdList);
        return appServerPoList.stream().collect(Collectors.groupingBy(AppServerPo::getJarName));
    }



}

